package flc.ast.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.OnBackPressedDispatcher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityCameraBinding;
import flc.ast.dialog.ScanTipDialog;
import flc.ast.utils.Content;
import flc.ast.view.CameraIndicator;
import stark.common.basic.utils.BitmapUtil;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.StkFlashUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    public static int type;
    private int mIndicator;//拍照模式
    private List<Integer> listIcon = new ArrayList<>();
    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private boolean isSecond;//是否为第二张图片
    private Bitmap firstBitmap, secondBitmap;
    private OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            if (isSecond) {
                isSecond = false;
                if (mIndicator == 1) {
                    mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ahkbk1);
                } else {
                    mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.asfzzm);
                }
            } else {
                finish();
            }
        }
    };

    @Override
    protected int onCreate() {
        getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.tvCameraBack.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.tvCameraImport.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivCameraFlash) {//闪光灯
            openFlash();
        } else if (id == R.id.tvCameraBack) {//返回
            getOnBackPressedDispatcher().onBackPressed();
        } else if (id == R.id.ivCameraStart) {//拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            mDataBinding.cameraView.takePictureSnapshot();
        } else if (id == R.id.tvCameraImport) {//相册导入
            getPermission();
        }
    }

    @Override
    protected void initData() {
        listIcon.add(R.drawable.acszk);
        listIcon.add(R.drawable.ahkbk1);
        listIcon.add(R.drawable.asfzzm);
        listIcon.add(R.drawable.acszk);
        listIcon.add(R.drawable.acszk);
        listIcon.add(R.drawable.ajszk);
        listIcon.add(R.drawable.ajszk);
        listIcon.add(R.drawable.acszk);
        listIcon.add(R.drawable.acszk);
        listIcon.add(R.drawable.acszk);

        List<String> tabs = Arrays.asList(getResources().getStringArray(R.array.document_arr));
        // 实现了 CameraIndicator.Tab 的对象
        List<CameraIndicator.Tab> tabList = new ArrayList<>();
        for (String tab : tabs) {
            tabList.add(() -> tab);
        }
        CameraIndicator.Tab[] map = tabList.toArray(new CameraIndicator.Tab[0]);
        // 将 tab 集合设置给 cameraIndicator，（binding.cameraIndicator 即 xml 布局里的控件）
        mDataBinding.cameraIndicator.setTabs(map);
        // 默认选中拍照
        mDataBinding.cameraIndicator.setCurrentIndex(type);
        mDataBinding.cameraIndicator.setOnSelectedChangedListener((index, tag) -> {
            mIndicator = index;
            if (index == 1 || index == 2) {
                showScanTipDialog();
            }
            isSecond = false;
            mDataBinding.ivRecCameraIcon.setImageResource(listIcon.get(mIndicator));
        });
        //初始化相机
        initCameraView();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {

            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        startAct(bitmap);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getImage();
                    }
                }).request();
    }

    private void getImage() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .minCount(1)
                .maxCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        ArrayList<String> pathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            pathList.add(entity.getTargetPath());
                        }
                        if (mIndicator == 1 || mIndicator == 2) {
                            if (isSecond) {
                                secondBitmap = ImageUtils.getBitmap(pathList.get(0));
                                ScanResultActivity.type = mIndicator;
                                ScanResultActivity.firstBitmap = firstBitmap;
                                ScanResultActivity.secondBitmap = secondBitmap;
                                startActivity(ScanResultActivity.class);
                            } else {
                                isSecond = true;
                                firstBitmap = ImageUtils.getBitmap(pathList.get(0));
                                if (mIndicator == 1) {
                                    mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ahkbk2);
                                } else {
                                    mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.asfzfm);
                                }
                            }
                        } else {
                            firstBitmap = ImageUtils.getBitmap(pathList.get(0));
                            ScanResultActivity.type = mIndicator;
                            ScanResultActivity.firstBitmap = firstBitmap;
                            startActivity(ScanResultActivity.class);
                        }
                    }
                });
    }

    private void startAct(Bitmap bitmap) {
        bitmap = cropCurBmp(bitmap);

        if (mIndicator == 1 || mIndicator == 2) {
            if (isSecond) {
                secondBitmap = bitmap;
                ScanResultActivity.type = mIndicator;
                ScanResultActivity.firstBitmap = firstBitmap;
                ScanResultActivity.secondBitmap = secondBitmap;
                startActivity(ScanResultActivity.class);
            } else {
                isSecond = true;
                firstBitmap = bitmap;
                if (mIndicator == 1) {
                    mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ahkbk2);
                } else {
                    mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.asfzfm);
                }
            }
        } else {
            firstBitmap = bitmap;
            ScanResultActivity.type = mIndicator;
            ScanResultActivity.firstBitmap = firstBitmap;
            startActivity(ScanResultActivity.class);
        }
    }

    private Bitmap cropCurBmp(Bitmap mCurBmp) {
        int[] olForRefer = new int[2];
        int[] olForPic = new int[2];
        mDataBinding.ivRecCameraIcon.getLocationInWindow(olForRefer);
        mDataBinding.cameraView.getLocationInWindow(olForPic);
        int x = olForRefer[0] - olForPic[0];
        x = (int) (mCurBmp.getWidth() * (x * 1f / mDataBinding.cameraView.getWidth()));

        int y = olForRefer[1] - olForPic[1];
        y = (int) (mCurBmp.getHeight() * (y * 1f / mDataBinding.cameraView.getHeight()));

        int width = (int) (mCurBmp.getWidth() * (mDataBinding.ivRecCameraIcon.getWidth() * 1f / mDataBinding.cameraView.getWidth()));
        if (x + width > mCurBmp.getWidth()) {
            width = mCurBmp.getWidth() - x;
        }
        int height = (int) (mCurBmp.getHeight() * (mDataBinding.ivRecCameraIcon.getHeight() * 1f / mDataBinding.cameraView.getHeight()));
        if (y + height > mCurBmp.getHeight()) {
            height = mCurBmp.getHeight() - y;
        }
        return ImageUtils.clip(mCurBmp, x, y, width, height, true);
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgdk);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgd);
        }
        StkFlashUtil.setFlashlightStatus(isFlash);
    }

    private void showScanTipDialog() {
        ScanTipDialog dialog = new ScanTipDialog(mContext);
        dialog.type = mIndicator;
        dialog.show();
    }

}